package com.itfenghuang.day12;

import java.util.concurrent.locks.ReentrantLock;

public class A02_Lock锁 {
    public static void main(String[] args) {
        /**
         *  使用lock锁解决多线程共享数据安全问题
         *   lock锁
         *     jdk5提供的  锁对象  lock是一个接口
         *
         *     实现类: ReentrantLock
         *     构造方法: public ReentrantLock()
         *          public void lock()   加锁
         *          public void unlock() 解锁\释放锁
         *     加锁
         *
         *     怎么去解决,只要不让出现多线程安全问题的环境
         *     同步技术: 同步方法 代码块 lock锁
         */
        SellTIcket s = new SellTIcket();
        Thread t1 = new Thread(s, "窗口1");
        Thread t2 = new Thread(s, "窗口2");
        Thread t3 = new Thread(s, "窗口3");
        t1.start();
        t2.start();
        t3.start();

    }
}
class SellTIcket implements Runnable{
    private int ticketTotal=100;
    //锁对象
    private ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //加锁
            lock.lock();
            if (ticketTotal>0){
                //获取线程名字
                System.out.println(Thread.currentThread().getName()+"卖出了第"+ticketTotal+"张票");
                ticketTotal--;
            }
            //释放锁对象
            lock.unlock();
            if (ticketTotal<=0){
                break;
            }
        }
    }
}